local Addon = {}

local mfname, mf9rank--, mf8rank

local casts, misses
local canmiss
local incombat

local function printf(...)
	DEFAULT_CHAT_FRAME:AddMessage(format(...))
end


local function assertcombat()
	if not incombat then
		casts, misses = 0, 0
		incombat = true
	end
end

local function check(unitid, name, rank)
	return unitid=='player' and name==mfname and rank==mf9rank
end

function Addon:UNIT_SPELLCAST_SENT(unitid, name, rank)
	if check(unitid, name, rank) then
		printf('sent')
		canmiss = true
	end
end

function Addon:UNIT_SPELLCAST_CHANNEL_START(unitid, name, rank)
	if check(unitid, name, rank) then
		printf('start')
		canmiss = nil
	end
end

function Addon:UNIT_SPELLCAST_SUCCEEDED(unitid, name, rank)
	if check(unitid, name, rank) then
		printf('succ')
		assertcombat()
		casts = casts+1
		if canmiss then
			printf('miss')
			misses = misses+1
			canmiss = nil
		end
	end
end
function Addon:UNIT_SPELLCAST_FAILED(unitid, name, rank)
	if check(unitid, name, rank) then
		printf('fail')
		canmiss = nil
	end
end

function Addon:PLAYER_REGEN_DISABLED()
	assertcombat()
end

function Addon:PLAYER_REGEN_ENABLED()
	incombat = false
	printf('MindFlayMisses: %d/%d casts missed (%.2f%%)', misses, casts, casts>0 and misses/casts*100 or 0)
end

do
	local frame = CreateFrame("Frame")
	frame:RegisterEvent("PLAYER_LOGIN")
	frame:SetScript('OnEvent', function(self, event, ...) 
		Addon[event](Addon, ...) 
	end)
	function Addon:PLAYER_LOGIN()
		mfname, mf9rank = GetSpellInfo(48156)
		casts, misses = 0, 0
		local v,build = GetBuildInfo()
		frame:RegisterEvent("UNIT_SPELLCAST_SENT")
		frame:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED")
		frame:RegisterEvent("UNIT_SPELLCAST_CHANNEL_START")
		frame:RegisterEvent("UNIT_SPELLCAST_FAILED")
		frame:RegisterEvent('PLAYER_REGEN_DISABLED')
		frame:RegisterEvent('PLAYER_REGEN_ENABLED')
	end
end
